package com.ios.common.filehanlder;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletResponse;

public class FileDownLoad {
	
	public static FileDownLoad getInstance(){
		return new FileDownLoad();
	}

	public String fileDownLoad(String resourcePath, HttpServletResponse response)
			throws Exception {
		File file = new File(resourcePath);
		String fileName = new String(file.getName().getBytes("gbk"),"iso8859-1");
		response.reset();
		response.setContentType("application/octet-stream; charset=UTF-8");
		response.addHeader("Content-Disposition", "attachment; filename="
				+ fileName);
		response.setContentLength((int) file.length());
		byte[] buffer = new byte[4096];
		BufferedOutputStream output = null;
		BufferedInputStream input = null;
		try {
			output = new BufferedOutputStream(response.getOutputStream());
			input = new BufferedInputStream(new FileInputStream(file.getPath()));

			int n = -1;
			while ((n = input.read(buffer, 0, 4096)) > -1) {
				output.write(buffer, 0, n);
			}

			response.flushBuffer();
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		} finally {
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}
		return "down_success";
	}

}
